import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { IResponse } from "@/types/index";

export default class MyHttp {
  instance: AxiosInstance;
  requestList: { [index: string]: AbortController };
  cancelRequestList: AbortController[];

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    this.requestList = {};
    this.cancelRequestList = [];
  }

  request(config: AxiosRequestConfig): Promise<AxiosResponse> {
    return new Promise((resolve, reject) => {
      const url = config.url;

      if (url) {
        if (this.requestList[url]) {
          this.requestList[url].abort();
          delete this.requestList[url];
          reject();
        } else {
          const controller = new AbortController();
          config.signal = controller.signal;
          this.requestList[url] = controller;

          this.instance
            .request(config)
            .then((res) => {
              if (res) {
                resolve(res);
              }
            })
            .catch((err: any) => {
              reject(err);
            })
            .finally(() => {
              if (this.requestList[url]) {
                delete this.requestList[url];
              }
            });
        }
      }
    });
  }
}
